package top.infopub.mgr.mkt.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.infopub.dto.mkt.BidBondRecycleDto;
import top.infopub.enums.hr.PostGroupEnum;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.enums.mkt.RecycleTypeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.exception.FlowProcessException;
import top.infopub.mgr.mkt.dao.BidBondRecycleDao;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.dao.ProjectInfoDao;
import top.infopub.mgr.mkt.jsonvo.BidBondRecycleJsonVo;
import top.infopub.mgr.mkt.service.BidBondRecycleService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.sys.service.RoleService;
import top.infopub.model.mkt.BidBondRecycle;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.model.mkt.ProjectInfo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BidBondRecycleServiceImpl implements BidBondRecycleService {
    @Autowired
    private BidBondRecycleDao bidBondRecycleDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    private Map<String, String> cwRoleIdMap = new HashMap<String, String>(){
        {
            put("A1BF48795AC4DDDCE055000000000001", "A1BF48795AC4DDDCE055000000000001");
        }
    };

    @Override
    public BidBondRecycleJsonVo queryDetailByProCode(String proCode, String bondApplyId) {
        BidBondRecycleJsonVo bidRecJson = new BidBondRecycleJsonVo();
        //基础信息
        BidBondRecycleDto bidRec = bidBondRecycleDao.queryDetailByProCode(proCode);
        bidRec.setBondApplyId(bondApplyId);

        //查询已回收总额
        BigDecimal sumDepoColltAmt = bidBondRecycleDao.sumDepoColltAmt(bondApplyId);
        if (sumDepoColltAmt == null) sumDepoColltAmt = new BigDecimal(0);
        bidRec.setSumDepoColltAmt(sumDepoColltAmt);
        bidRecJson.setInfo(bidRec);

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(proCode, ProjectFileTypeEnum.FILE_TYPE44.getCode(), null);
        bidRecJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return bidRecJson;
    }

    @Override
    public BidBondRecycleJsonVo queryDetailById(String id) {
        BidBondRecycleJsonVo bidRecJson = new BidBondRecycleJsonVo();
        //基础信息
        BidBondRecycleDto bidRec = bidBondRecycleDao.queryDetailById(id);

        //查询已回收总额
        BigDecimal sumDepoColltAmt = bidBondRecycleDao.sumDepoColltAmt(bidRec.getBondApplyId());
        if (sumDepoColltAmt == null) sumDepoColltAmt = new BigDecimal(0);
        bidRec.setSumDepoColltAmt(sumDepoColltAmt);
        bidRecJson.setInfo(bidRec);

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(bidRec.getProCode(), ProjectFileTypeEnum.FILE_TYPE44.getCode(), null);
        bidRecJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return bidRecJson;
    }

    @Override
    public RspVo editDetail(BidBondRecycle bidBondRecycle, List<ProjectAttachment> attachmentList, AuthorizationVO vo, Integer submitType) {
        //根据pro_code查询项目基础信息
        ProjectInfo tmpProInfo = projectInfoDao.findByProCode(bidBondRecycle.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");
        BidBondRecycleDto bidRecDto = bidBondRecycleDao.queryDetailByProCode(bidBondRecycle.getProCode());
        if (bidRecDto == null) return RspVo.getFailureResponse(400, "保证金数据不存在");

        //更新附件信息
        projectAttachmentDao.deleteByWhere(bidBondRecycle.getProCode(), ProjectFileTypeEnum.FILE_TYPE44.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (StringUtils.isBlank(bidBondRecycle.getId())) {
            BigDecimal sumDepoColltAmt = bidBondRecycleDao.sumDepoColltAmt(bidBondRecycle.getBondApplyId());
            if (sumDepoColltAmt == null) sumDepoColltAmt = new BigDecimal(0);
            if (sumDepoColltAmt.add(bidBondRecycle.getDepositCollection()).compareTo(bidRecDto.getBondMoney()) == 1) {
                return RspVo.getFailureResponse(400, "回收金额大于投标保证金支付金额");
            }
            if (StringUtils.isNotBlank(bidBondRecycle.getPayee())
                    || StringUtils.isNotBlank(bidBondRecycle.getBankAccount())
                    || bidBondRecycle.getActualAmountPayment() != null
                    || bidBondRecycle.getActualDatePayment() != null
                    || StringUtils.isNotBlank(bidBondRecycle.getRemarks())) {
                throw new FlowProcessException("财务信息需财务人员填写");
            }
            bidBondRecycle.setCodes(IdFactory.getUUIDUpper());
            bidBondRecycle.setAddBy(vo.getId());
            bidBondRecycle.setAddTime(new Date());
            bidBondRecycle.setUptBy(vo.getId());
            bidBondRecycle.setUptTime(new Date());
            bidBondRecycleDao.insertBySeletive(bidBondRecycle);

            String detailJson = JSON.toJSONString(queryDetailById(bidBondRecycle.getId()));
            if (StringUtils.equals(RecycleTypeEnum.INQ_TYPE0.getCode(), bidBondRecycle.getBailMethodRecycle())) {
                //现金方式
                proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE17, detailJson, bidBondRecycle.getId(), bidBondRecycle.getProCode(), vo);
            } else if (StringUtils.equals(RecycleTypeEnum.INQ_TYPE1.getCode(), bidBondRecycle.getBailMethodRecycle())) {
                //其他方式
                proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE14, detailJson, bidBondRecycle.getId(), bidBondRecycle.getProCode(), vo);
            } else {
                throw new FlowProcessException("请选择回收方式");
            }
        } else {
            /**
             * 目前阶段id存在的情况是发待办给财务，财务进来如果是现金回收填写财务信息保存
             * 条件：
             * 1.记录存在
             * 2.回收方式是现金
             * 3.当前保证金回收记录是审批通过的
             * 4.当前登录人员属于对应公司/区域公司的财务组人员
             */
            BidBondRecycle tmpBbr = bidBondRecycleDao.selectByPrimaryKey(bidBondRecycle.getId());
            if (tmpBbr == null) throw new FlowProcessException("保证金回收信息不存在");
            if (!StringUtils.equals(RecycleTypeEnum.INQ_TYPE0.getCode(), tmpBbr.getBailMethodRecycle())) {
                throw new FlowProcessException("回收方式不正确");
            }
            if (!StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpBbr.getProcessStatus())) {
                throw new FlowProcessException("审批状态不正确，编辑失败");
            }
            String orgId = queryOrgIdByProAddBy(bidBondRecycle.getProCode());
            int count = checkIsCwFlag(PostGroupEnum.FINANCE.getCode(), orgId, vo.getId());
            if (count <= 0) throw new FlowProcessException("无权限编辑保证金回收数据");
            if (StringUtils.isBlank(bidBondRecycle.getPayee())
                    || StringUtils.isBlank(bidBondRecycle.getBankAccount())
                    || bidBondRecycle.getActualAmountPayment() == null
                    || bidBondRecycle.getActualDatePayment() == null
                    || StringUtils.isBlank(bidBondRecycle.getRemarks())) {
                throw new FlowProcessException("缺少必填参数");
            }
            BidBondRecycle bidBr = new BidBondRecycle();
            bidBr.setId(bidBondRecycle.getId());
            bidBr.setUptBy(vo.getId());
            bidBr.setUptTime(new Date());
            bidBr.setPayee(bidBondRecycle.getPayee());
            bidBr.setBankAccount(bidBondRecycle.getBankAccount());
            bidBr.setActualAmountPayment(bidBondRecycle.getActualAmountPayment());
            bidBr.setActualDatePayment(bidBondRecycle.getActualDatePayment());
            bidBr.setRemarks(bidBondRecycle.getRemarks());
            bidBondRecycleDao.updateBySeletive(bidBondRecycle);
            //发起流程
            String detailJson = JSON.toJSONString(queryDetailById(bidBondRecycle.getId()));
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE20, detailJson, bidBondRecycle.getId(), tmpBbr.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public BidBondRecycle selectByPrimaryKey(String id) {
        return bidBondRecycleDao.selectByPrimaryKey(id);
    }

    @Override
    public String queryOrgIdByProAddBy(String proCode) {
        return bidBondRecycleDao.queryOrgIdByProAddBy(proCode);
    }

    @Override
    public int checkIsCwFlag(String groupId, String orgId, String id) {
        return bidBondRecycleDao.checkIsCwFlag(groupId, orgId, id);
    }
}
